Page({
  data: {
    dates: [],
    selectedDate: '',
    todayDate: '',
    clickedIndex: null,
    timeSlots: [], // 后面动态生成
    courts: [],    // 后端返回的场地预约情况
    selectedCourt: null,
    selectedTimes: [], // 选中的时段数组
    totalPrice: 0,
    selectedHours: 0,
    userInfo: { id: 1, balance: 100 } // 模拟当前登录用户，后续可替换真实登录信息
  },

  onLoad: function () {
    this.updateDateList();
    this.generateTimeSlots();
    this.fetchCourts();
  },

  updateDateList: function () {
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth() + 1;
    const day = today.getDate();
    const weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][today.getDay()];
    const todayDate = `${month}.${day}`;
    const selectedDate = `${year}-${month}-${day} ${weekday}`;

    const dates = [];
    for (let i = 0; i < 10; i++) {
      const newDate = new Date(today.getTime() + i * 24 * 60 * 60 * 1000);
      const newMonth = newDate.getMonth() + 1;
      const newDay = newDate.getDate();
      const newWeekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][newDate.getDay()];
      dates.push({
        date: `${newMonth}.${newDay}`,
        weekday: newWeekday
      });
    }

    this.setData({ dates, selectedDate, todayDate });
  },

  changeDate: function (e) {
    const index = e.currentTarget.dataset.index;
    const date = e.currentTarget.dataset.date;
    const weekday = e.currentTarget.dataset.weekday;
    const selectedDate = `${this.data.selectedDate.split(' ')[0].split('-')[0]}-${date.split('.')[0]}-${date.split('.')[1]} ${weekday}`;
    this.setData({ selectedDate, clickedIndex: index });
    this.fetchCourts(); // 切换日期时刷新场地信息
  },

  generateTimeSlots: function () {
    const startHour = 7;
    const endHour = 22;
    const interval = 30; // 每30分钟
    const slots = [];

    for (let h = startHour; h <= endHour; h++) {
      ['00', '30'].forEach(min => {
        if (h === endHour && min !== '00') return;
        slots.push({
          time: `${h < 10 ? '0' + h : h}:${min}`,
          courts: [false, false, false, false, false, false] // 初始为可约
        });
      });
    }
    this.setData({ timeSlots: slots });
  },

  fetchCourts: function () {
    wx.request({
      url: 'http://127.0.0.1:5000/court/list',
      method: 'GET',
      success: (res) => {
        if (res.data.code === 200) {
          const updatedSlots = this.data.timeSlots.map(slot => ({
            ...slot,
            courts: res.data.data[slot.time] || [false, false, false, false, false, false]
          }));
          this.setData({ timeSlots: updatedSlots });
        } else {
          wx.showToast({ title: '场地加载失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '请求失败，请稍后重试', icon: 'none' });
      }
    });
  },

  selectCourt: function (e) {
    const { timeIndex, courtIndex } = e.currentTarget.dataset;
    const timeSlot = this.data.timeSlots[timeIndex];

    if (timeSlot.courts[courtIndex]) {
      wx.showToast({ title: '已被预约', icon: 'none' });
      return;
    }

    // 标记选中的时间段和球场
    this.setData({
      selectedCourt: courtIndex,
      selectedTimes: [timeIndex],
      totalPrice: 30, // 假设每半小时30元
      selectedHours: 0.5
    });
  },

  submitReservation: function () {
    if (!this.data.selectedCourt || this.data.selectedTimes.length === 0) {
      wx.showToast({ title: '请选择时间段', icon: 'none' });
      return;
    }

    const timeIndex = this.data.selectedTimes[0];
    const start_time = this.data.timeSlots[timeIndex].time;
    const end_time = this.calculateEndTime(start_time, 30); // 默认半小时

    wx.request({
      url: 'http://127.0.0.1:5000/order/create',
      method: 'POST',
      data: {
        user_id: this.data.userInfo.id,
        court_id: this.data.selectedCourt + 1, // 后端一般场地id从1开始
        start_time: start_time,
        end_time: end_time
      },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({ title: '预约成功', icon: 'success' });
          this.fetchCourts();
        } else {
          wx.showToast({ title: res.data.msg, icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '提交失败', icon: 'none' });
      }
    });
  },

  calculateEndTime: function (start, minutes) {
    const [h, m] = start.split(':').map(Number);
    const totalMins = h * 60 + m + minutes;
    const endH = Math.floor(totalMins / 60);
    const endM = totalMins % 60;
    return `${endH < 10 ? '0' + endH : endH}:${endM === 0 ? '00' : endM}`;
  }
});
